import type { HomeType } from '../home/interface'
import type { HomeTrainerType } from './interface'
import { observer, useLocalObservable, useObserver } from 'mobx-react'
import { stores } from '@/stores'
import { fetchDispatchTask, fetchEvaluateList, fetchHomeData } from './api'
import { useEffect } from 'react'
import { GroupData } from '../home/components'
import { pick } from '@/utils/share'
import { Button } from 'antd-mobile'
import { history } from 'umi'
import { EvaluateList } from './components/EvaluateCard'
import NoticeSwiper from '../home/components/NoticeSwiper/index'
import Plate from './components/Plate'
import styles from './index.module.less'
import arrowDown from '@/static/homeTrainer/arrows_down.png'
import arrowUp from '@/static/homeTrainer/arrows_up.png'
import useWelcomeByRole from '../home/hooks/useWelcomeByRole'

type trainerInfo = Omit<HomeType.Data, 'group_data'> & {
    group_data: Pick<HomeType.Data['group_data'], 'real_total' | 'student_total'>
    dispatchTaskList: HomeTrainerType.DispatchTask[]
    evaluateList: HomeTrainerType.Evaluate[]
}

/** 待派遣任务列表 */
const DispatchTaskList = <T extends HomeTrainerType.DispatchTask>(props: {
    list: T[]
    onClickItem?: (item: T) => any
    maxShow?: number
}) => {
    const { maxShow = 3 } = props

    const store = useLocalObservable(() => ({
        /** 是否展开 */
        expand: false,
    }))

    const allList = props.list.filter(item => item.is_confirm === 0)

    const showList = allList.slice(0, maxShow)
    /** 当前展示的数据 - {@link store.expand} */
    const currentData = store.expand ? allList : showList

    return useObserver(() => {
        return currentData.length ? (
            <>
                {currentData.map(item => {
                    return (
                        <div key={item.id} className={styles.dispatchTaskCard}>
                            <div className={styles.dispatchTaskCard_content}>
                                <div className={styles.dispatchTaskCard_header}>
                                    <span>{item.name}</span>
                                </div>
                                <div className={styles.dispatchTaskCard_date}>
                                    {item.begin_date}
                                </div>
                            </div>

                            <Button
                                style={{ flexShrink: 0 }}
                                color="primary"
                                shape="rounded"
                                size="small"
                                disabled={item.is_confirm !== 0}
                                onClick={() => props.onClickItem?.(item)}
                            >
                                接受派遣
                            </Button>
                        </div>
                    )
                })}

                {allList.length > maxShow && (
                    <div className={styles.dispatchTask_more}>
                        <Button
                            fill="none"
                            size="small"
                            onClick={() => (store.expand = !store.expand)}
                        >
                            <img
                                className={styles.dispatchTask_icon}
                                src={store.expand ? arrowUp : arrowDown}
                            />
                        </Button>
                    </div>
                )}
            </>
        ) : (
            <span className={styles.plate_empty}>暂无派遣任务</span>
        )
    })
}

export default observer(() => {
    const { userStore } = stores
    const { nowTime, nowWeekly, welcome } = useWelcomeByRole()

    const store = useLocalObservable(() => ({
        /** 教师首页详细信息 */
        trainerInfo: {
            group_data: {},
            dispatchTaskList: [] as Record<string, any>[],
            evaluateList: [] as Record<string, any>[],
        } as trainerInfo,

        async fetchTrainerInfoToStore() {
            const data = await fetchHomeData()
            if (!data) return

            store.trainerInfo.group_data = pick(data.group_data, ['real_total', 'student_total'])
        },

        async fetchDispatchTaskListToStore() {
            const data = await fetchDispatchTask()
            store.trainerInfo.dispatchTaskList = data
        },

        async fetchEvaluateListToStore() {
            /** 讲师待办作业暂时为空 */
            if (stores.userStore.isTutor) {
                store.trainerInfo.evaluateList = []
                return
            }
            const data = await fetchEvaluateList()
            store.trainerInfo.evaluateList = data
        },
    }))

    const { isStudentRole, isTeacherRole, isTutor } = stores.userStore
    const permission = {
        evaluateList: [isStudentRole, isTutor].some(v => v === true),
        dispatchTask: isTeacherRole,
        groupData: isTeacherRole,
        notice: isTeacherRole,
    }

    useEffect(() => {
        store.fetchTrainerInfoToStore()
        store.fetchDispatchTaskListToStore()
        if (permission.evaluateList) {
            store.fetchEvaluateListToStore()
        }
    }, [permission.evaluateList, store])

    /** 填写 */
    const onClickEvaluate = (item: HomeTrainerType.Evaluate) => {
        console.log(item.id)
        history.push({
            pathname: '/qualityEvaluate/write',
            query: {
                evaluateId: String(item.evaluate_id),
                groupId: String(item.group_id),
                listId: String(item.id),
            },
        })
    }

    /** 接受派遣 */
    const onClickDispatchTask = async () => {
        history.push({
            pathname: '/train',
        })
        // try {
        //     await acceptTask(item.id)
        //     Toast.show({
        //         icon: 'success',
        //         content: '派遣成功',
        //     })
        //     store.fetchDispatchTaskListToStore()
        // } catch (error) {}
    }

    return (
        <div className={styles.page}>
            <div className={styles.header}>
                <div className={styles.header_welcome}>
                    {welcome}，{userStore.getUserInfo?.realname}
                </div>

                <div className={styles.header_date}>
                    {nowTime} {nowWeekly}
                </div>
            </div>

            {permission.notice && <NoticeSwiper className={styles.header_banner} />}

            {permission.groupData && (
                <GroupData className={styles.groupData} data={store.trainerInfo.group_data} />
            )}

            <div>
                {permission.dispatchTask && (
                    <Plate className={styles.plate} title="待派遣任务">
                        <DispatchTaskList
                            list={store.trainerInfo.dispatchTaskList}
                            onClickItem={onClickDispatchTask}
                        />
                    </Plate>
                )}

                {permission.evaluateList && (
                    <Plate className={styles.plate} title="待办作业">
                        <EvaluateList
                            emptyClass={styles.plate_empty}
                            list={store.trainerInfo.evaluateList}
                            onClickItem={onClickEvaluate}
                        />
                    </Plate>
                )}
            </div>
        </div>
    )
})
